package com.lvmama.rhino.web;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lvmama.rhino.entity.MongoCondition;
import com.lvmama.rhino.entity.PageMongo;
import com.lvmama.rhino.entity.PieRobot;
import com.lvmama.rhino.mongo.RhinoRound;
import com.lvmama.rhino.mongo.RhinoTalk;
import com.lvmama.rhino.pojo.RhinoSatisfaction;
import com.lvmama.rhino.pojo.RobotData;
import com.lvmama.rhino.service.MongoService;
import com.lvmama.rhino.service.RobotService;
import com.lvmama.rhino.utils.FilenameUtils;


/**
 * 说明：客服机器人
 * @author yecan
 * @date 2016年7月22日
 */
@Controller
@RequestMapping("robot")
public class RobotController {

	@Autowired
	private RobotService robotService;
	@Autowired
	private MongoService mongoService;
	
	/**
	 * 
	* @Title: ajaxData 
	* @Description: 查询客服机器人昨日数据
	* @param @param province
	* @param @param chooseTime
	* @param @return
	* @param @throws IOException    设定文件 
	* @return RobotData    返回类型 
	* @throws
	 */
	@RequiresPermissions("sys:robot:view")
	@RequestMapping("ajaxData")
	@ResponseBody
	public RobotData ajaxData(@RequestParam("province") String province ,@RequestParam("chooseTime") String chooseTime) throws IOException {
	    String[] split = chooseTime.split("-");
        DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
        Date startDate = DateTime.parse(split[0].trim()+ " 00:00:00", formater).toDate();
        Date endDate = DateTime.parse(split[1].trim()+ " 23:59:59", formater).toDate();
        //首次点击进去默认查询全国的数据
	    if("全国".equals(province)){
			RobotData queryAllData = robotService.queryAllData(startDate,endDate);
			return queryAllData;
		}
		return robotService.queryRobotData(province,startDate,endDate);
	}
	
	@RequiresPermissions("sys:robot:view")
	@RequestMapping("mongo")
	public String queryByPage(@RequestParam(value="page",defaultValue="1") Integer page,Model model){
		List<RhinoRound> queryByPage = mongoService.queryByPage(page, 10);
		Long count=mongoService.queryCount();
		PageMongo pageMongo=new PageMongo();
		if((int)page<=1){
			pageMongo.setIsFirstPage(true);
		}
		pageMongo.setPrePage(page-1);
		pageMongo.setNextPage(page+1);
		
		pageMongo.setLastPage((int)(count%10==0?count/10:count/10+1));
		if((int)page==(int)pageMongo.getLastPage()){
			pageMongo.setIsLastPage(true);
		}
		pageMongo.setPages(pageMongo.getLastPage());
		pageMongo.setPageNum(page);
		model.addAttribute("mongos",queryByPage);
		model.addAttribute("page",pageMongo);
		return "application/robotMongo";
	}
	
	@RequiresPermissions("sys:robot:view")
	@RequestMapping("ajaxMongoData")
	public String ajaxMongoData(MongoCondition condition,Model model){
		if(StringUtils.isEmpty(condition.getBeginDate()) && StringUtils.isNotEmpty(condition.getEndDate())){
			model.addAttribute("message", "请输入开始时间");
			model.addAttribute("condition", condition);
			return "application/robotMongo";
		}
		
		if(StringUtils.isNotEmpty(condition.getBeginDate()) && StringUtils.isEmpty(condition.getEndDate())){
			model.addAttribute("message", "请输入截止时间");
			model.addAttribute("condition", condition);
			return "application/robotMongo";
		}
		if(StringUtils.isEmpty(condition.getIsMatch())){
			condition.setIsMatch("NOT_MATCH");
		}
		//增加服务商查询条件
		if(StringUtils.isEmpty(condition.getSource())){
			condition.setSource("all");
		}
		if(StringUtils.isEmpty(condition.getPage())){
			condition.setPage("1");
		}
		 //默认点击菜单进去，查询昨天数据
		 if(StringUtils.isEmpty(condition.getBeginDate()) && StringUtils.isEmpty(condition.getEndDate())){
			 Calendar   cal   =   Calendar.getInstance();
			 cal.add(Calendar.DATE,-1);
			 String i = cal.get(Calendar.YEAR)+"";
			 String j = cal.get(Calendar.MONTH)+1+"";
			 String k = cal.get(Calendar.DAY_OF_MONTH)+"";
			 if(j.length()==1){
				 j="0"+j;
			 }
			 if(k.length()==1){
				 k="0"+k;
			 }
			 condition.setBeginDate(i+"-"+j+"-"+k+" 00:00:00");
			 condition.setEndDate(i+"-"+j+"-"+k+" 23:59:59");
		 }
		 DateTimeFormatter formater = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
		 Date startDate=null;
		 if(StringUtils.isNotEmpty(condition.getBeginDate())){
		 startDate = DateTime.parse(condition.getBeginDate(), formater).toDate();
		 }
		 Date endDate=null;
		 if(StringUtils.isNotEmpty(condition.getEndDate())){
	        endDate = DateTime.parse(condition.getEndDate(), formater).toDate();
		 }
		
		
		 List<RhinoRound> queryByPage = mongoService.ajaxByPage(Integer.valueOf(condition.getPage()),startDate,endDate,condition.getIsMatch(),condition.getSource());
		 //数据库中暂时没有存用户手机号
		 /*	for (RhinoRound rhinoRound : queryByPage) {
			if(rhinoRound!=null && StringUtils.isNotBlank(rhinoRound.getSessionId())){
				RhinoTalk rhinoTalk=mongoService.queryTalkBySessionId(rhinoRound.getSessionId());
				if(rhinoTalk==null){
					rhinoRound.setMobileNumber("匿名用户");
					continue;
				}
				rhinoRound.setMobileNumber(StringUtils.isBlank(rhinoTalk.getMobileNumber())?"匿名用户":rhinoTalk.getMobileNumber());
			}
		}*/
		Long count=mongoService.queryAjaxCount(startDate,endDate,condition.getIsMatch(),condition.getSource());
		Integer page=Integer.valueOf(condition.getPage());
		PageMongo pageMongo=new PageMongo();
		if((int)page<=1){
			pageMongo.setIsFirstPage(true);
		}
		pageMongo.setPrePage((page-1)<1?1:page-1);
		
		
		pageMongo.setLastPage((int)(count%8==0?count/8:count/8+1));
		pageMongo.setNextPage((page+1)>pageMongo.getLastPage()?pageMongo.getLastPage():(page+1));
		if((int)page==(int)pageMongo.getLastPage()){
			pageMongo.setIsLastPage(true);
		}
		pageMongo.setPages(pageMongo.getLastPage());
		pageMongo.setPageNum(page);
		model.addAttribute("mongos",queryByPage);
		model.addAttribute("page",pageMongo);
		model.addAttribute("condition", condition);
		return "application/robotMongo";
	}
	
	@RequestMapping("ajaxPie")
	@ResponseBody
	public List<PieRobot> ajaxPie(MongoCondition condition){
		 DateTimeFormatter formater = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
		 Date startDate=null;
		 if(StringUtils.isNotEmpty(condition.getBeginDate())&& !"undefined".equalsIgnoreCase(condition.getBeginDate())){
		 startDate = DateTime.parse(condition.getBeginDate(), formater).toDate();
		 }
		 Date endDate=null;
		 if(StringUtils.isNotEmpty(condition.getEndDate()) && !"undefined".equalsIgnoreCase(condition.getBeginDate())){
	        endDate = DateTime.parse(condition.getEndDate(), formater).toDate();
		 }
		return mongoService.ajaxPie(startDate,endDate);
		
	}
	
	
	@RequiresPermissions("sys:robot:export")
	@RequestMapping("exportMongoData")
	public void exportData(MongoCondition condition,HttpServletResponse response,HttpServletRequest request) throws IOException {
		 DateTimeFormatter formater = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
		 Date startDate=null;
		 if(StringUtils.isNotEmpty(condition.getBeginDate())&& !"undefined".equalsIgnoreCase(condition.getBeginDate())){
		 startDate = DateTime.parse(condition.getBeginDate(), formater).toDate();
		 }
		 Date endDate=null;
		 if(StringUtils.isNotEmpty(condition.getEndDate()) && !"undefined".equalsIgnoreCase(condition.getBeginDate())){
	        endDate = DateTime.parse(condition.getEndDate(), formater).toDate();
		 }
		 List<RhinoRound> list=mongoService.exportMongoData(condition.getIsMatch(),startDate,endDate,condition.getSource());
		 
		 if(list!=null && list.size()!=0){
			 	HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
				HSSFSheet sheet = hssfWorkbook.createSheet("客服机器人命中率");
				HSSFRow headerRow = sheet.createRow(0);
				headerRow.createCell(0).setCellValue("sessionId");
				headerRow.createCell(1).setCellValue("问题");
				headerRow.createCell(2).setCellValue("回答");
				headerRow.createCell(3).setCellValue("是否命中");
				headerRow.createCell(4).setCellValue("服务商");
				headerRow.createCell(5).setCellValue("创建时间");
				sheet.setColumnWidth(0, 35*256);
				sheet.setColumnWidth(1, 30*256);
				sheet.setColumnWidth(2, 150*256);
				sheet.setColumnWidth(3, 20*256);
				sheet.setColumnWidth(4,20*256);
				sheet.setColumnWidth(5,20*256);
			 for (int i=0;i<list.size();i++) {
				 HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
				 dataRow.createCell(0).setCellValue(list.get(i).getSessionId());
				 dataRow.createCell(1).setCellValue(list.get(i).getQuestion());
				 dataRow.createCell(2).setCellValue(list.get(i).getAnswer());
				 dataRow.createCell(3).setCellValue(list.get(i).getStatus());
				 dataRow.createCell(4).setCellValue(list.get(i).getSource());
				 dataRow.createCell(5).setCellValue(list.get(i).getCreateTime().toLocaleString());
			}
			 	String downloadFilename="命中率.xls";
				String contentType=request.getSession().getServletContext().getMimeType(downloadFilename);
				response.setContentType(contentType);
				String agent=request.getHeader("user-agent");
				downloadFilename=FilenameUtils.encodeDownloadFilename(downloadFilename,agent);
				String contentDisposition="attachment;filename="+downloadFilename;
				response.setHeader("Content-Disposition", contentDisposition);
				hssfWorkbook.write(response.getOutputStream());
		 }
		 
	}
	
	 @RequiresPermissions("sys:robot:view")
	 @RequestMapping("satisfaction")
	 public String findSatisfactionData(MongoCondition condition,Model model){
		 if(StringUtils.isEmpty(condition.getBeginDate()) && StringUtils.isNotEmpty(condition.getEndDate())){
				model.addAttribute("message", "请输入开始时间");
				model.addAttribute("condition", condition);
				return "application/satisfaction";
			}
			
			if(StringUtils.isNotEmpty(condition.getBeginDate()) && StringUtils.isEmpty(condition.getEndDate())){
				model.addAttribute("message", "请输入截止时间");
				model.addAttribute("condition", condition);
				return "application/satisfaction";
			}
			//默认点击菜单进去，查询昨天数据
			 if(StringUtils.isEmpty(condition.getBeginDate()) && StringUtils.isEmpty(condition.getEndDate())){
				 Calendar   cal   =   Calendar.getInstance();
				 String i = cal.get(Calendar.YEAR)+"";
				 String j = cal.get(Calendar.MONTH)+1+"";
				 String k = cal.get(Calendar.DAY_OF_MONTH)+"";
				 if(j.length()==1){
					 j="0"+j;
				 }
				 if(k.length()==1){
					 k="0"+k;
				 }
				 condition.setBeginDate(i+"-"+j+"-"+k+" 00:00:00");
				 condition.setEndDate(i+"-"+j+"-"+k+" 23:59:59");
			 }
			 //默认服务商为全选
			 if(StringUtils.isEmpty(condition.getSource())){
				 condition.setSource("all");
			 }
			 
		 DateTimeFormatter formater = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
		 Date startDate=null;
		 if(StringUtils.isNotEmpty(condition.getBeginDate())&& !"undefined".equalsIgnoreCase(condition.getBeginDate())){
		 startDate = DateTime.parse(condition.getBeginDate(), formater).toDate();
		 }
		 Date endDate=null;
		 if(StringUtils.isNotEmpty(condition.getEndDate()) && !"undefined".equalsIgnoreCase(condition.getBeginDate())){
	        endDate = DateTime.parse(condition.getEndDate(), formater).toDate();
		 }
		 if(StringUtils.isEmpty(condition.getPage())){
				condition.setPage("1");
			}
		 List<RhinoTalk> findSatisfactionData = mongoService.findSatisfactionData(condition.getSatisfactionDegree(),condition.getPage(), startDate, endDate,condition.getSource());
		
		 Long count = mongoService.queryTalkCount(condition.getSatisfactionDegree(),startDate, endDate,condition.getSource());
		 Integer page=Integer.valueOf(condition.getPage());
		 PageMongo pageMongo=new PageMongo();
			if((int)page<=1){
				pageMongo.setIsFirstPage(true);
			}
			pageMongo.setPrePage((page-1)<1?1:page-1);
			
			
			pageMongo.setLastPage((int)(count%12==0?count/12:count/12+1));
			pageMongo.setNextPage((page+1)>pageMongo.getLastPage()?pageMongo.getLastPage():page+1);
			if((int)page==(int)pageMongo.getLastPage()){
				pageMongo.setIsLastPage(true);
			}
			pageMongo.setPages(pageMongo.getLastPage());
			pageMongo.setPageNum(page);
		  model.addAttribute("mongos",findSatisfactionData);
		  model.addAttribute("page",pageMongo);
		  model.addAttribute("condition", condition);
		 return "application/satisfaction";
		 
	 }
	 
	 @RequiresPermissions("sys:robot:view")
	 @RequestMapping("viewTalkData")
	 @ResponseBody
	 public RhinoSatisfaction viewTalkData(@RequestParam("sessionId")String sessionId,@RequestParam(value="page",defaultValue="1")Integer page){
		 Map<String,String> map=new HashMap<>();
		 map.put("MATCH", "命中");
		 map.put("NOT_MATCH","未命中");
		 map.put("EXCEPTION", "异常");
		 List<RhinoRound> queryBySessionId = mongoService.queryBySessionId(page, sessionId);
		 //若问题为空显示为自动回答
		 for (RhinoRound rhinoRound : queryBySessionId) {
			if(rhinoRound!=null && StringUtils.isBlank(rhinoRound.getQuestion())){
				rhinoRound.setQuestion("自动回答");
			}
			if(rhinoRound!=null){
				if(StringUtils.isNotBlank(rhinoRound.getInternalStatus())){
					rhinoRound.setInternalStatus(map.get(rhinoRound.getInternalStatus()));
				}
				if(StringUtils.isBlank(rhinoRound.getInternalStatus())){
					rhinoRound.setInternalStatus("暂无");
				}
			}
		}
		 RhinoSatisfaction rhinoSatisfaction=new RhinoSatisfaction();
		 rhinoSatisfaction.setQuestionAndAnswer(queryBySessionId);
		 if(page<=1){
			 rhinoSatisfaction.setPrePage(1); 
		 }else{
			 rhinoSatisfaction.setPrePage(page-1);
		 }
		 Long count = mongoService.queryCountBySessionId(sessionId);
		 rhinoSatisfaction.setTotalPage((int)(count%3==0?count/3:count/3+1));
		 rhinoSatisfaction.setPageNum(page);
		 if(page>=rhinoSatisfaction.getTotalPage()){
		 rhinoSatisfaction.setNextPage(rhinoSatisfaction.getTotalPage());
		 }else{
		 rhinoSatisfaction.setNextPage(page+1); 
		 }
		 return rhinoSatisfaction;
	 }
	 
	 	@RequestMapping("ajaxSatisfactionPie")
		@ResponseBody
		public List<PieRobot> ajaxSatisfactionPie(MongoCondition condition){
			 DateTimeFormatter formater = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
			 Date startDate=null;
			 if(StringUtils.isNotEmpty(condition.getBeginDate())&& !"undefined".equalsIgnoreCase(condition.getBeginDate())){
			 startDate = DateTime.parse(condition.getBeginDate(), formater).toDate();
			 }
			 Date endDate=null;
			 if(StringUtils.isNotEmpty(condition.getEndDate()) && !"undefined".equalsIgnoreCase(condition.getBeginDate())){
		        endDate = DateTime.parse(condition.getEndDate(), formater).toDate();
			 }
			return mongoService.ajaxSatisfactionPie(startDate,endDate);
		}
	 	
}
